/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/


function cloneObject(o) {
    return $.extend({}, o);
 return eval(uneval(o));
}


var AdminBlocker = {
    ajaxUrl : '',
    pageid : '',
    numBlocks : Array(),
    page : new Object,
    hashRegistry : Array(),

    init : function(pageid, workspaceid){
        this.ajaxUrl = AjaxUrl;
        this.pageid = pageid;
        this.workspaceid = workspaceid;
        var pageEl = $('#jfxpage-'+pageid).get(0);
        this.page.id = 'jfxpage-'+pageid;
        this.page.pageid = pageid;
        this.page.elements = Array();
        this.page.deletedBlocks = Array();
        this.rebuildPage();
        this.drawToolbar();
    },

    drawToolbar :

    getValue : function(id, alt){
        for(var i=0; i<this.hashRegistry.length; i++){
            if(this.hashRegistry[i].id == id) return this.hashRegistry[i].val;
        }
        return alt;
    },

    getKey : function(id){
        for(var i=0; i<this.hashRegistry.length; i++){
            if(this.hashRegistry[i].id == id) return i;
        }
        var key = this.hashRegistry.length;
        this.hashRegistry[key] = new Object();
        return key;
    },

    setValue : function(id, val){
        var key = this.getKey(id);
        //alert(key+' '+id+' '+val);
        this.hashRegistry[key].id = id;
        this.hashRegistry[key].val = val;
    },

    rebuildPage : function(){
        $.getJSON(AdminBlocker.ajaxUrl+'/get-page-elements/', {page : this.pageid}, AdminBlocker.doRebuildPage);
    },

    doRebuildPage : function(page){
        for(var i=0; i<page.elements.length; i++){
            AdminBlocker.addElementToPage(page.elements[i], AdminBlocker.page.id);
        };
        AdminBlocker.showArrows();
        $(".jfx-block").mouseover(function(event){
                        //$(this).width($(this).width()+2);
                        //$(this).height($(this).height()+2);
                        //if(AdminBlocker.highlightedBlock) $(AdminBlocker.highlightedBlock).css('background-color', $(AdminBlocker.highlightedBlock).attr('old-bg-color'));

                        var src = (event.srcelement) ? event.srcelement : event.target;
                        if(src.id != this.id) return;

                        if(AdminBlocker.currentHoveredBlock && AdminBlocker.currentHoveredBlock.id != src.id){
                            //alert('unsetting '+AdminBlocker.currentHoveredBlock.id+' to '+AdminBlocker.getValue(AdminBlocker.currentHoveredBlock.id+' background-color'));
                            $(AdminBlocker.currentHoveredBlock).css('background-color', AdminBlocker.getValue(AdminBlocker.currentHoveredBlock.id+' background-color'));
                        }
                        
                        

                        if($(this).css('background-color')=='rgb(0, 0, 255)') return;
                        AdminBlocker.setValue(this.id+' background-color', $(this).css('background-color'));
                        //$(this).css("background-color", '#355D8C');
                        AdminBlocker.currentHoveredBlock = this;
                    });

    },

    addElementToPage : function(el, parentId, regenerateId){
        
        var blockDetails = cloneObject(el.details);
        if(typeof(this.numBlocks[blockDetails.module_key])==='undefined') this.numBlocks[blockDetails.module_key] = 0;
        else this.numBlocks[blockDetails.module_key]++;

        if(parentId === this.page.id){
            var parentElement = this.page;
            blockDetails.page_parent = 1;
        }else{
            var parentElement = this.findElement(this.page.elements, parentId);
            alert('making page parent = 0');
            blockDetails.page_parent = 0;
        }

        blockDetails.parent_id = parentId;
        blockDetails.page_id = this.pageid;
        blockDetails.pageid = this.pageid;

        if(regenerateId === true){
            var newid = 'jfxpage-'+this.pageid+'-'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key];
            while(document.getElementById(newid)){
                this.numBlocks[blockDetails.module_key]++;
                newid = 'jfxpage-'+this.pageid+'-'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key];
                //alert('trying for '+newid);
            };
            blockDetails.id = newid;
            if(document.getElementById(newid)){
                alert('There is an error, we already have '+newid+', but this is what we found when trying to add element to page!!!');
                return;
            }
            //blockDetails.id = 'page_'+this.pageid+'_module_'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key]+'-'+this.workspaceid;

            $.post(AdminBlocker.ajaxUrl+'/copy-block-lang/', {origid : el.id, newid : blockDetails.id, details : JSON.stringify(blockDetails)});
        

        }

        var i = parentElement.elements.length;
        parentElement.elements[i] = new Object;
        var element = parentElement.elements[i];

        var contentArea = document.createElement('div');
        contentArea.className = 'jfx-content-area';
        contentArea.innerHTML = blockDetails.default_content;
        //alert('def:'+blockDetails.content);

        var newEl = document.createElement('div');

//        alert('class name: '+blockDetails.class_name);

        newEl.id = blockDetails.id;
        $(newEl).attr('class', blockDetails.class_name+' jfx-block');
        if(blockDetails.is_droppable == 1) $(newEl).attr('class', $(newEl).attr('class')+' jfx-droppable');
        
        $('#'+parentId).append(newEl);
        this.createBlockActions(newEl, blockDetails);
        $(newEl).click(function(event){
            var src = (event.srcelement) ? event.srcelement : event.target;
            while(!src.className.match('jfx-block')) src = src.parentNode;
            //alert(src.id+' vs '+this.id);
            if(src.id != this.id) return;
            $(AdminBlocker.visibleActions).css('display', 'none');
            $('#jfx-actions_'+this.id).css('display', 'block');
            $('#jfx-actions-wrapper').css('display', 'block');
            AdminBlocker.visibleActions = $('#jfx-actions_'+this.id).get(0);;
        });


        $(newEl).append(contentArea);

        //alert(newEl.id+' '+newEl.class_name+' '+newEl.innerHTML);

        element.id = blockDetails.id;
        element.elements = Array();
        element.details = blockDetails;

        $.getJSON(AdminBlocker.ajaxUrl+'/get-block-content/', {block : el.id, insertid : blockDetails.id}, AdminBlocker.insertBlockContent);
        $.getJSON(AdminBlocker.ajaxUrl+'/get-block-style/', {block : el.id, insertid : blockDetails.id}, AdminBlocker.updateBlockStyle);

        
        for(var i=0; i<el.elements.length; i++){
            AdminBlocker.addElementToPage(el.elements[i], blockDetails.id, regenerateId);
        }

    },

    autoSavePage : function(){
        var useResponseFunction = false;
        var responseFunction = function(){};
        this.savePage(useResponseFunction, responseFunction);
    },

    savePage : function(useResponseFunction, responseFunction){
        if(useResponseFunction!==true){
            this.callSaveResponseFunction = false;
            this.saveResponseFunction = responseFunction;
        }else{
            this.callSaveResponseFunction = true;
            this.saveResponseFunction = responseFunction;
        }
        
        
        var json = JSON.stringify(this.page);
        //var json = this.page.serialize();
        var data = {
            'type' : 'post',
            'datatype' : 'json',
            'data' : json
        }
        //$.getJSON(AjaxUrl+'/save-page', data, this.confirmSave);
        $.post(AjaxUrl+'/save-page/', data, this.confirmSave);
        //alert(json);
    },

    confirmSave : function(json){
        json = JSON.parse(json);
        if(AdminBlocker.callSaveResponseFunction!==true) return;
        if(json.status == 'OK') AdminBlocker.saveResponseFunction(true);
        else AdminBlocker.saveResponseFunction(false, json.message);
    },

    addBlock : function(el, blockDetails){
        //alert(blockDetails.module_key);
        if(typeof(this.numBlocks[blockDetails.module_key])==='undefined') this.numBlocks[blockDetails.module_key] = 0;
        else this.numBlocks[blockDetails.module_key]++;

        var blockDetails = cloneObject(blockDetails);//.clone();
        if(el.id === this.page.id){
            var parentElement = this.page;
            blockDetails.page_parent = 1;
        }else{
            var parentElement = this.findElement(this.page.elements, el.id);
            alert('addblock making page parent = 0');
            blockDetails.page_parent = 0;
        }

        var origBlockDetails = cloneObject(blockDetails);

        blockDetails.parent_id = parentElement.id;
        blockDetails.page_id = this.pageid;
        blockDetails.workspace_id = this.workspaceid;
        //blockDetails.id = 'page_'+this.pageid+'_module_'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key]+'-'+this.workspaceid;
        var newid = 'jfxpage-'+this.pageid+'-'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key];
        while(document.getElementById(newid)){
            this.numBlocks[blockDetails.module_key]++;
            newid = 'jfxpage-'+this.pageid+'-'+blockDetails.module_key+'-'+this.numBlocks[blockDetails.module_key];
            //alert('trying for '+newid);
        };
        //alert('found a unique id: '+newid+'!!!');
        blockDetails.id = newid;
        if(document.getElementById(newid)){
            alert('There is an error, we already have '+newid+', but this is what we found when trying to add block to page!!!');
            return;
        }

        if(origBlockDetails.id != newid){
            $.post(AdminBlocker.ajaxUrl+'/copy-block-lang/', {origid : origBlockDetails.id, newid : newid, details : JSON.stringify(blockDetails)});
            
        }

        blockDetails.is_droppable = 1;
        
        var i = parentElement.elements.length;
        parentElement.elements[i] = new Object;
        var element = parentElement.elements[i];

        var contentArea = document.createElement('div');
        contentArea.className = 'jfx-content-area';
        contentArea.innerHTML = blockDetails.default_content;

        var newEl = document.createElement('div');
        newEl.id = blockDetails.id;
        $(newEl).attr('class', blockDetails.class_name+' jfx-droppable jfx-block');
        
        $(el).append(newEl);
        this.createBlockActions(newEl, blockDetails);
        $(newEl).click(function(event){
            var src = (event.srcelement) ? event.srcelement : event.target;
            while(!src.className.match('jfx-block')) src = src.parentNode;
            if(src.id != this.id) return;
            $(AdminBlocker.visibleActions).css('display', 'none');
            $('#jfx-actions_'+this.id).css('display', 'block');
            $('#jfx-actions-wrapper').css('display', 'block');
            AdminBlocker.visibleActions = $('#jfx-actions_'+this.id).get(0);
        });
        /*$(newEl).mouseleave(function(event){
            $('.jfx-actions', this).css('display', 'none');
        });*/

        $(newEl).append(contentArea);

        element.id = blockDetails.id;
        element.elements = Array();
        element.details = blockDetails;

        $.getJSON(AdminBlocker.ajaxUrl+'/get-block-content/', {block : origBlockDetails.id, insertid: element.id}, AdminBlocker.insertBlockContent);
        if(typeof(blockDetails.elements)=='object'){
            for(var i=0; i<blockDetails.elements.length; i++){
                AdminBlocker.addElementToPage(blockDetails.elements[i], element.id, true);
            }
        }
        this.autoSavePage();
        this.showArrows();
    },

    createBlockActions : function(el, details){
        $(el).css('position', 'relative');
        var actions = document.createElement('div');
        $(actions).css('background-color', 'black');
        actions.className = 'jfx-actions';
        actions.id = 'jfx-actions_'+el.id;

 
        // heading
        var h3 = document.createElement('h3');
        h3.id = 'jeditableh3_'+el.id;
        h3.className = h3.id;
        $(h3).text(details.title);
        $(h3).click(function(){
            AdminBlocker.currentEditingH3 = this;
        });
        var editableFunction = function(value, settings){
            var h3 = AdminBlocker.currentEditingH3;
            var id = h3.id.replace('jeditableh3_', '');
            var arr = AdminBlocker.findElement(AdminBlocker.page.elements, id);
            arr.details.title = value;
            AdminBlocker.autoSavePage();
            return value;
        };
        var editableSettings = {
            'type' : 'text',
            'submit' : 'OK',
            'id' : this.id,
            'width' : '240'
        };
        $(h3).editable(editableFunction, editableSettings);

        $(actions).append(h3);

        // delete button
        var del = document.createElement('a');
        del.className = 'jfx-delete';
        del.href = 'javascript: void(null)';
        del.id = 'delete-'+el.id;
        $(del).click(function(){
            AdminBlocker.deleteBlock(this.id);
        });
        var delImage = document.createElement('img');
        delImage.src = ImageUrl+'/admin/icons/delete.gif';
        delImage.title = 'Delete Block';
        //$(del).text('Delete');
        $(del).append(delImage);
        actions.appendChild(del);


        // edit button
        var edit = document.createElement('a');
        edit.href = 'javascript: void(null)';
        edit.id = 'edit-'+el.id;
        edit.className = 'jfx-edit';
        $(edit).click(function(){
            AdminBlocker.editBlock(this.id);
        });
        var editImage = document.createElement('img');
        editImage.src = ImageUrl+'/admin/icons/edit.gif';
        editImage.title = 'Edit Content';
        //$(edit).text('Edit');
        $(edit).append(editImage);
        actions.appendChild(edit);



        // style
        var style = document.createElement('a');
        style.href = 'javascript: void(null)';
        style.id = 'style-'+el.id;
        $(style).click(function(){
            AdminBlocker.styleBlock(this.id);
        });
        var styleImage = document.createElement('img');
        styleImage.src = ImageUrl+'/admin/icons/style.gif';
        styleImage.title = 'Edit Styles';
        //$(style).text('Style');
        $(style).append(styleImage);
        actions.appendChild(style);


        // save template button
        var save = document.createElement('a');
        save.href = 'javascript: void(null)';
        save.id = 'a-'+el.id;
        $(save).click(function(){
            AdminBlocker.saveTemplate(this.id);
        });
        var saveImage = document.createElement('img');
        saveImage.src = ImageUrl+'/admin/icons/save.gif';
        saveImage.title = 'Save as Template';
        //$(save).text('Save Template');
        $(save).append(saveImage);
        actions.appendChild(save);



        //$('#jfx-header').append(actions);
        //$(el).append(actions);
        $('#jfx-actions-wrapper').draggable();
        $('#jfx-actions-wrapper').append(actions);
        $(actions).css('display', 'none');
        //$(actions).css('position', 'fixed');
        $(actions).css('bottom', 0);
    },

    showArrows : function(){
        $('.jfx-actions .jfx-arrow').each(function(){
            this.parentNode.removeChild(this);
        });
        
        var pageBlocks = $('.jfx-block').get();



        for(var i0 = 0; i0<pageBlocks.length; i0++){
            var el = pageBlocks[i0];


            if($('>.jfx-block', el.parentNode).get().length>1){
                var els = $('>.jfx-block', el.parentNode).get();
                var first = false;
                var last = false;
                for(var i=0; i<els.length; i++){
                    if($('>.jfx-block', el.parentNode).get(i).id == el.id){
                        if(i==0) first = true;
                        else if(i == (els.length-1)) last = true;
                    }
                }
                if(!first){
                    // show the up arrow
                    var arrow = document.createElement('a');
                    arrow.className = 'jfx-arrow';
                    arrow.id = 'arrowup-'+el.id;
                    var arrowImg = document.createElement('img');
                    arrowImg.src = ImageUrl+'/admin/icons/up.png';
                    arrowImg.alt = 'Up';
                    arrowImg.title = 'Move Up';
                    $(arrow).append(arrowImg);
                    $(arrow).click(function(){
                        var id = this.id;
                        id = id.split('-');
                        id = id.splice(1);
                        id = id.join('-');
                        AdminBlocker.moveUp(id);
                    });
                    $('#jfx-actions_'+el.id).get(0).appendChild(arrow);
                }
                if(!last){
                    // show the down arrow
                    var arrow = document.createElement('a');
                    arrow.className = 'jfx-arrow';
                    arrow.id = 'arrowdown-'+el.id;
                    var arrowImg = document.createElement('img');
                    arrowImg.src = ImageUrl+'/admin/icons/down.png';
                    arrowImg.alt = 'Down';
                    arrowImg.title = 'Move Down';
                    $(arrow).append(arrowImg);
                    $(arrow).click(function(){
                        var id = this.id;
                        id = id.split('-');
                        id = id.splice(1);
                        id = id.join('-');
                        AdminBlocker.moveDown(id);
                    });
                    $($('#jfx-actions_'+el.id).get(0)).append(arrow);
                }else{
                    // no arrows shown, it is the only element
                }
            }

        }

    },

    moveUp : function(id){
        var el = $('#'+id).get(0);
        var parent = this.findParent(this.page, el.id);
        var key = this.findKey(parent, el.id);
        if(key == 0) return;
        var newKey = key-1;
        var tmpEl = parent.elements[key];
        parent.elements[key] = parent.elements[newKey];
        parent.elements[newKey] = tmpEl;
        var els = $(el.parentNode).children('.jfx-block');
        $(els[newKey]).before(el);
        AdminBlocker.autoSavePage();
        AdminBlocker.showArrows();
    },

    moveDown : function(id){
        var el = $('#'+id).get(0);
        var parent = this.findParent(this.page, el.id);
        var key = this.findKey(parent, el.id);
        if(key == (parent.elements.length-2)) return;
        var newKey = key+1;
        var tmpEl = parent.elements[key];
        parent.elements[key] = parent.elements[newKey];
        parent.elements[newKey] = tmpEl;
        var els = $(el.parentNode).children('.jfx-block');
        $(els[newKey]).after(el);
        AdminBlocker.autoSavePage();
        AdminBlocker.showArrows();
    },

    saveTemplate : function(id){
        id = id.split('-');
        id.splice(0, 1);
        id = id.join('-');
        var url = AjaxUrl+'/save-block-template/';
        var el = this.findElement(this.page.elements, id);

        $.post(url, {id : id, title: el.details.title, element: JSON.stringify(el)}, AdminBlocker.confirmSaveBlockTemplate);
    },

    confirmSaveBlockTemplate : function(json){
        json = JSON.parse(json);
        if(json.status == 'OK') alert('Save success!');
    },

    editBlock : function(id){
        id = id.split('-');
        id.splice(0, 1);
        id = id.join('-');
        var parent = document.getElementById(id).parentNode;
        var href = AjaxUrl+'/edit-block-instance/?id='+id+'&parent='+parent.id+'&KeepThis=true&TB_iframe=true&height=500&width=700';
        tb_show('Editing Block Details', href, false);
        AdminBlocker.editingBlockId = id;
        $("#TB_window").unload(function () {
            $.getJSON(AdminBlocker.ajaxUrl+'/get-block-content/', {block : AdminBlocker.editingBlockId}, AdminBlocker.insertBlockContent);
        });
    },

    styleBlock : function(id){
        id = id.split('-');
        id.splice(0, 1);
        id = id.join('-');
        var parent = document.getElementById(id).parentNode;
        var href = AjaxUrl+'/style-block/?id='+id+'&parent='+parent.id+'&KeepThis=true&TB_iframe=true&height=500&width=700';
        tb_show('Styling Block', href, false);
        AdminBlocker.editingBlockId = id;
        $("#TB_window").unload(function () {
            $.getJSON(AdminBlocker.ajaxUrl+'/get-block-style/', {block : AdminBlocker.editingBlockId}, AdminBlocker.updateBlockStyle);
            $.getJSON(AdminBlocker.ajaxUrl+'/get-block-content/', {block : AdminBlocker.editingBlockId}, AdminBlocker.insertBlockContent);
        });
    },

    updateBlockStyle : function(style){
       
        var el = $('#'+style.id).get(0);
       
        $(el).attr('style', style.block_style);
        if(style.is_droppable==1) style.class_name += ' jfx-droppable';
        style.class_name += ' jfx-block';
        el.className = style.class_name;
    },

    insertBlockContent : function(content){
        
        $('#'+content.id+' .jfx-content-area').get(0).innerHTML = content.content;
        //alert('inserted '+content.id+' '+content.content);
        $('#'+content.id+' .jfx-content-area form').get(function(){
            this.action = 'javascript: void(null)';
        });
    },

    deleteBlock : function(id){
        id = id.split('-');
        id.splice(0, 1);
        id = id.join('-');
        var el = this.findElement(this.page.elements, id);
        if(el.elements.length > 0){
            if(confirm('This block has '+el.elements.length+' child blocks, are you sure you want to delete it?')){
                var node = $('#'+el.id).get(0);
                var parentEl = this.findParent(this.page, el.id);
                var k = this.findKey(parentEl, el.id);
                parentEl.elements.splice(k, 1);
                this.regenerateKeys(parentEl);
                node.parentNode.removeChild(node);
            }
        }else{
            var node = $('#'+el.id).get(0);
            var parentEl = this.findParent(this.page, el.id);
            var k = this.findKey(parentEl, el.id);
            parentEl.elements.splice(k, 1);
            this.regenerateKeys(parentEl);
            node.parentNode.removeChild(node);
        }
        this.page.deletedBlocks[this.page.deletedBlocks.length] = id;
        this.autoSavePage();
        if($('.jfx-block', this.page.id).get().length == 0){
            $('#jfx-actions-wrapper').css('display', 'none');
        }
    },

    findParent : function(el, id){
        if(el.elements.length == 0) return false;
        var parentNode = el;
        for(var i=0; i<el.elements.length; i++){
            if(el.elements[i].id == id){
                return parentNode;
            }
            else if(el.elements[i].elements.length > 0){
                var found = this.findParent(el.elements[i], id);
                if(typeof(found) == 'object'){
                    return found;
                }
            }
        }
        return false;
    },

    findKey : function(el, id){
        if(el.elements.length == 0) return false;
        for(var i=0; i<el.elements.length; i++){
            if(el.elements[i].id == id) return i;
        };
    },

    regenerateKeys : function(arr, type){
        if(!type) type = 'object';
        var count = 0;
        var newArr = Array();
        for(var i=0; i<arr.length; i++){
            if(typeof(arr[i])==type){
                newArr[count] = arr[i];
                count++;
            };
        };
        arr = newArr;
    },

    findElement : function(elements, id){
        for(var i=0; i<elements.length; i++){
            if(elements[i].id == id){
                return elements[i];
            }
            else if(elements[i].elements.length > 0){
                var found = this.findElement(elements[i].elements, id);
                if(found !== false){
                    return found;
                }
            }
        }
        return false;
    }
}


























